﻿//=====================
//系统通用方法
//Jerzy Jiang
//2015-03-13
//=====================
/*
 * 2017-05-23 JintangLiang 增加通用下载文件方法DownloadFile()
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Data.OleDb;

using System.Reflection;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.Zip;

namespace PacoToolKit
{
    public class Common
    {
        private static Object thisLock = new Object();
        /// <summary>
        /// 是否是数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNumeric(string value)
        {
            if (string.IsNullOrEmpty(value.Trim()))
                return false;
            else
                return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
        }

        /// <summary>
        /// 判断是否是日期
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsDate(string value)
        {
            bool result = true;
            try
            {
                DateTime.Parse(value);
            }
            catch
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="_str">被验证数据</param>
        /// <param name="_alidItem">正则表达式</param>
        /// <returns></returns>
        public static bool IsValidString(string _str, string _validItem)
        {
            return Regex.IsMatch(_str, _validItem);
        }

        /// <summary>
        /// 把任意的变量转换成字符串，如果是null或者DBNull.Value，返回String.Empty
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>字符串，至少是String.Empty</returns>
        public static string ToString(object _obj)
        {
            string m_Result = String.Empty;

            if (_obj == DBNull.Value || _obj == null)
            {
                m_Result = String.Empty;
            }
            else
            {
                m_Result = Convert.ToString(_obj);
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量转换成整形，如果该变量不能转换成整形，返回0
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>整形，至少是0</returns>
        public static int ToInt32(object _obj)
        {
            int m_Result = 0;

            try
            {
                m_Result = Convert.ToInt32(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        ///  把任意的变量转换成长整形，如果该变量不能转换成整形，返回0
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>整形，至少是0</returns>
        public static long ToInt64(object _obj)
        {
            long m_Result = 0;

            try
            {
                m_Result = Convert.ToInt64(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量转换为double形，如果该变量不能转换为double,返回0
        /// </summary>
        /// <param name="_obj"></param>
        /// <returns></returns>
        public static double ToDouble(object _obj)
        {
            Double m_Result = 0;

            try
            {
                m_Result = Convert.ToDouble(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量转换为decimal形，如果该变量不能转换为decimal,返回0
        /// </summary>
        /// <param name="_obj"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object _obj)
        {
            decimal m_Result = 0;

            try
            {
                m_Result = Convert.ToDecimal(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量装换成布尔，如果该变量不能转换成布尔，返回false
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>布尔，至少是false</returns>
        public static bool ToBoolean(object _obj)
        {
            bool m_Result = false;

            try
            {
                m_Result = Convert.ToBoolean(_obj);
            }
            catch (Exception)
            {
                m_Result = false;
            }

            return m_Result;
        }

        /// <summary>
        /// 转换Json的特殊字符
        /// </summary>
        /// <param name="value">String对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJosn(string _value)
        {
            if (string.IsNullOrEmpty(_value))
            {
                return string.Empty;
            }

            string temstr;
            temstr = _value;
            temstr = temstr.Replace("&nbsp;&nbsp;", "");
            temstr = temstr.Replace("{", "｛");
            temstr = temstr.Replace("}", "｝");
            temstr = temstr.Replace(":", "：");
            temstr = temstr.Replace(",", "，");
            temstr = temstr.Replace("[", "【");
            temstr = temstr.Replace("]", "】");
            temstr = temstr.Replace(";", "；");
            temstr = temstr.Replace("\n", "<br/>");
            temstr = temstr.Replace("\r", "");
            temstr = temstr.Replace("\t", "   ");
            temstr = temstr.Replace("'", "’");
            temstr = temstr.Replace(@"\", @"\\");
            temstr = temstr.Replace("\"", "“");
            temstr = temstr.Replace("\"", "”");
            return temstr;
        }

        public static string TransChar(string value)
        {
            string theString = value.Replace(">", "&gt;");
            theString = theString.Replace("<", "&lt;");
            theString = theString.Replace(" ", "&nbsp;");
            theString = theString.Replace("\"", "&quot;");
            theString = theString.Replace("\'", "&#39;");
            theString = theString.Replace("\\", "\\\\");//对斜线的转义  
            theString = theString.Replace("\n", "\\n");  //注意php中替换的时候只能用双引号"\n"
            theString = theString.Replace("\r", "\\r");
            return theString;
        }

        /// <summary>
        /// 转义字符还原
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string EscapeHtml(string value)
        {
            return value.Replace("&amp;", "&").Replace("&quot;", "\"").Replace("&#39;", "'").Replace("&lt;", "<").Replace("&gt;", ">");
        }
        /// <summary>
        /// 返回一个32位 Guid 如 “FDKSDFJ32LK3W24SDD5F4SD56FS35F4S”全球唯一标示符
        /// </summary>
        /// <returns></returns>
        public static string GetGUID()
        {
            return System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
        }

        ///<summary>
        ///防止SQL注入式攻击
        ///</summary>
        ///<param name="inputString">where条件</param>
        public static string ConvertSql(string inputString)
        {
            inputString = inputString.ToLower();
            inputString = inputString.Trim(); //去空格
            inputString = inputString.Replace("'", ""); //去单引号
            inputString = inputString.Replace(";", ""); //去分号
            inputString = inputString.Replace("=", ""); //去等号
            inputString = inputString.Replace(" or ", ""); //去 or
            inputString = inputString.Replace(" and ", ""); //去 and
            inputString = inputString.Replace(" like ", ""); //去 通配符
            inputString = inputString.Replace(";--", ""); //去注释
            inputString = inputString.Replace("insert ", "").Replace("insert/**/", ""); //去插入语句
            inputString = inputString.Replace("update ", "").Replace("update/**/", ""); //去修改语句
            inputString = inputString.Replace("delete ", "").Replace("delete/**/", ""); //去删除语句
            inputString = inputString.Replace("create ", "").Replace("create/**/", ""); //去新建语句
            inputString = inputString.Replace("exec ", "").Replace("exec/**/", ""); //去执行语句
            inputString = inputString.Replace("drop ", "").Replace("drop/**/", ""); //去删除语句
            inputString = inputString.Replace("truncate ", ""); //去清表语句
            inputString = inputString.Replace("xp_cmdshell", ""); //
            return inputString;
        }

        public static string RandomName(string FileName)
        {
            string StrReturn = FileName;
            StrReturn += DateTime.Now.ToString("yyyyMMddhhmmss");
            StrReturn += "_";
            StrReturn += new Random().Next(1000000, 99999999).ToString();
            StrReturn += System.IO.Path.GetExtension(FileName);
            return StrReturn;
        }

        ////--------------------------------------------------------------------------------------------------------------------------------------------------------
        //public static void MailTo(string _toMail, string _title, string _content, SystemConfig _config)
        //{

        //    if (!string.IsNullOrEmpty(_toMail))
        //    {
        //        try
        //        {
        //            _toMail = _toMail.Replace("，", ",").Trim().Trim(',').Trim();
        //            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        //            client.Host = "mail.teczs.com";
        //            client.UseDefaultCredentials = true;

        //            client.Credentials = new System.Net.NetworkCredential(_config.Email, _config.Password);
        //            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

        //            string[] arrMail = _toMail.Split(',');
        //            foreach (string mail in arrMail)
        //            {
        //                if (!string.IsNullOrEmpty(mail))
        //                {
        //                    try
        //                    {
        //                        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(_config.Email, mail);
        //                        message.Subject = _title;
        //                        message.Body = _content;
        //                        message.BodyEncoding = System.Text.Encoding.UTF8;
        //                        message.IsBodyHtml = true;
        //                        client.Send(message);
        //                        TraceApp(mail + "\t\t" + _title);
        //                    }
        //                    catch (Exception exx)
        //                    {
        //                        Application_Error_Server("Common/MailTo()\n" + mail + "\n" + _title + "\n" + _content, exx);
        //                        clsOutMail outMail = new clsOutMail();
        //                        outMail.Address = mail;
        //                        outMail.Title = _title;
        //                        outMail.Body = _content;
        //                        outMail.WriteTime = DateTime.Now.ToString();
        //                        outMail.Times = outMail.Times + 1;
        //                        outMail.Add();
        //                    }
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            Application_Error_Server("Common/MailTo()\n" + _toMail + "\n" + _title + "\n" + _content, ex);
        //        }
        //    }
        //}

        //public static void ScanMail()
        //{
        //    try
        //    {
        //        SystemConfig config = new SystemConfig();
        //        IList<clsOutMail> mailList = clsOutMail.GetMailList_noSend();
        //        foreach (clsOutMail mail in mailList)
        //        {
        //            try
        //            {
        //                MailTo(mail.Address, mail.Title, mail.Body, config);
        //                mail.Delete();
        //            }
        //            catch (Exception ex1)
        //            {
        //                Application_Error_Server("Common/ScanMail(1)\n" + mail.Address + "\n" + mail.Title + "\n" + mail.Body, ex1);
        //            }
        //        }
        //    }
        //    catch (Exception ex2)
        //    {
        //        Application_Error_Server("Common/ScanMail(2)", ex2);
        //    }
        //}

        //internal static void MailTo()
        //{
        //    throw new Exception("The method or operation is not implemented.");
        //}



        /*
        public static MemoryStream WriteDataToExcel(DataSet ds)
        {
            MemoryStream memoryStream = new MemoryStream();

            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                foreach (DataTable table in ds.Tables)
                {
                    ISheet sheet = workbook.CreateSheet(table.TableName);
                    IRow headerRow = sheet.CreateRow(0);

                    foreach (DataColumn column in table.Columns)
                    {
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                    }

                    int rowIndex = 1;

                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);

                        foreach (DataColumn column in table.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }

                        rowIndex++;
                    }

                    sheet = null;
                    headerRow = null;
                }

                workbook.Write(memoryStream);

                workbook = null;
            }
            catch (Exception exception)
            {
                throw exception;
            }

            return memoryStream;
        }

        public static DataSet ExcelToDataSet(string excelPath)
        {
            return ExcelToDataSet(excelPath, true);
        }

        public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader)
        {
            int sheetCount;
            return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount);
        }

        public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount)
        {
            using (DataSet ds = new DataSet())
            {
                using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
                {
                    HSSFWorkbook workbook = new HSSFWorkbook(fileStream);

                    HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);

                    sheetCount = workbook.NumberOfSheets;

                    for (int i = 0; i < sheetCount; ++i)
                    {
                        HSSFSheet sheet = workbook.GetSheetAt(i) as HSSFSheet;
                        DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
                        ds.Tables.Add(dt);
                    }

                    return ds;
                }
            }
        }

        public static DataTable ExcelToDataTable(string excelPath, string sheetName)
        {
            return ExcelToDataTable(excelPath, sheetName, true);
        }

        public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool firstRowAsHeader)
        {
            using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = null;
                IFormulaEvaluator evaluator = null;
                ISheet sheet = null;
                if (excelPath.EndsWith(".xls"))
                {
                    workbook = new HSSFWorkbook(fileStream);
                    evaluator = new HSSFFormulaEvaluator(workbook);
                    sheet = workbook.GetSheet(sheetName) as HSSFSheet;
                    if (sheet == null)
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    workbook = new XSSFWorkbook(fileStream);
                    evaluator = new XSSFFormulaEvaluator(workbook);
                    sheet = workbook.GetSheet(sheetName) as XSSFSheet;
                    if (sheet == null)
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }

                return ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
            }
        }

        private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator, bool firstRowAsHeader)
        {
            if (firstRowAsHeader)
            {
                return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
            }
            else
            {
                return ExcelToDataTable(sheet, evaluator);
            }
        }

        private static DataTable ExcelToDataTableFirstRowAsHeader(ISheet sheet, IFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                IRow firstRow = sheet.GetRow(0) as IRow;
                int cellCount = GetCellCount(sheet);

                for (int i = 0; i < cellCount; i++)
                {
                    if (firstRow.GetCell(i) != null)
                    {
                        dt.Columns.Add(firstRow.GetCell(i).StringCellValue ?? string.Format("F{0}", i + 1), typeof(string));
                    }
                    else
                    {
                        dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
                    }
                }

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i) as IRow;
                    DataRow dr = dt.NewRow();
                    FillDataRowByHSSFRow(row, evaluator, ref dr);
                    dt.Rows.Add(dr);
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }

        private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator)
        {
            using (DataTable dt = new DataTable())
            {
                if (sheet.LastRowNum != 0)
                {
                    int cellCount = GetCellCount(sheet);

                    for (int i = 0; i < cellCount; i++)
                    {
                        dt.Columns.Add(string.Format("F{0}", i), typeof(string));
                    }

                    for (int i = 0; i < sheet.FirstRowNum; ++i)
                    {
                        DataRow dr = dt.NewRow();
                        dt.Rows.Add(dr);
                    }

                    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i) as IRow;
                        DataRow dr = dt.NewRow();
                        FillDataRowByHSSFRow(row, evaluator, ref dr);
                        dt.Rows.Add(dr);
                    }
                }

                dt.TableName = sheet.SheetName;
                return dt;
            }
        }

        private static void FillDataRowByHSSFRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr)
        {
            if (row != null)
            {
                for (int j = 0; j < dr.Table.Columns.Count; j++)
                {
                    ICell cell = row.GetCell(j) as ICell;

                    if (cell != null)
                    {
                        switch (cell.CellType)
                        {
                            case CellType.Blank:
                                dr[j] = DBNull.Value;
                                break;
                            case CellType.Boolean:
                                dr[j] = cell.BooleanCellValue;
                                break;
                            case CellType.Numeric:
                                if (DateUtil.IsCellDateFormatted(cell))
                                {
                                    dr[j] = cell.DateCellValue;
                                }
                                else
                                {
                                    dr[j] = cell.NumericCellValue;
                                }
                                break;
                            case CellType.String:
                                dr[j] = cell.StringCellValue;
                                break;
                            case CellType.Error:
                                dr[j] = cell.ErrorCellValue;
                                break;
                            case CellType.Formula:
                                cell = evaluator.EvaluateInCell(cell) as ICell;
                                dr[j] = cell.ToString();
                                break;
                            default:
                                throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
                        }
                    }
                }
            }
        }

        private static int GetCellCount(ISheet sheet)
        {
            int firstRowNum = sheet.FirstRowNum;

            int cellCount = 0;

            for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
            {
                IRow row = sheet.GetRow(i) as IRow;

                if (row != null && row.LastCellNum > cellCount)
                {
                    cellCount = row.LastCellNum;
                }
            }

            return cellCount;
        }
         * */


        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="xml">XML字符</param>
        /// <returns></returns>
        public static T DeserializeToObject<T>(string xml)
        {
            T myObject;
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            StringReader reader = new StringReader(xml);
            myObject = (T)serializer.Deserialize(reader);
            reader.Close();
            return myObject;
        }

        /// <summary>
        /// 将自定义对象序列化为XML字符串
        /// </summary>
        /// <param name="myObject">自定义对象实体</param>
        /// <returns>序列化后的XML字符串</returns>
        public static string SerializeToXml<T>(T myObject)
        {
            if (myObject != null)
            {
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));

                MemoryStream stream = new MemoryStream();
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                writer.Formatting = Formatting.None;//缩进
                xs.Serialize(writer, myObject);

                stream.Position = 0;
                StringBuilder sb = new StringBuilder();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        sb.Append(line);
                    }
                    reader.Close();
                }
                writer.Close();
                return sb.ToString();
            }
            return string.Empty;
        }

        /// <summary>
        /// 字符串转Base64字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StringToBase64(string str)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(str);
            return Convert.ToBase64String(b);
        }
        /// <summary>
        /// Base64字符串转普通字符串
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static string Base64ToString(string base64)
        {
            byte[] byteArray = Convert.FromBase64String(base64);
            return System.Text.Encoding.UTF8.GetString(byteArray);
        }

        /// <summary>
        /// C#反射遍历对象属性
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="model">对象</param>
        public static List<string> ForeachClassProperties<T>(T model)
        {
            List<string> names = new List<string>();
            Type t = model.GetType();
            PropertyInfo[] PropertyList = t.GetProperties();
            foreach (PropertyInfo item in PropertyList)
            {
                string name = item.Name;
                object value = item.GetValue(model, null);
                names.Add(name);
            }
            return names;
        }

        #region 根据属性名称获取值
        /// <summary>
        /// 根据属性名称获取值
        /// </summary>
        /// <param name="obj">对象实例</param>
        /// <param name="strAttribute">属性名</param>
        /// <returns>object</returns>
        public static object GetValueByStrAttribute(object obj, string strAttribute)
        {
            System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
            var value = propertyInfoName.GetValue(obj, null);

            if (propertyInfoName.PropertyType.FullName == "System.Int32")
            {
                return Common.ToInt32(value);
            }
            else if (propertyInfoName.PropertyType.FullName == "System.Decimal")
            {
                return Common.ToDecimal(value);
            }
            else if (propertyInfoName.PropertyType.FullName == "System.Double")
            {
                return Common.ToDouble(value);
            }
            else if (propertyInfoName.PropertyType.FullName == "System.Boolean")
            {
                return Common.ToBoolean(value);
            }
            else
            {
                return Common.ToString(value);
            }

        }
        #endregion

        #region 根据属性名称设置值
        /// <summary>
        /// 根据属性名称设置值
        /// </summary>
        /// <param name="obj">对象实例</param>
        /// <param name="strAttribute">属性名</param>
        /// <param name="value">值</param>
        public static void SetValueByStrAttribute(object obj, string strAttribute, object value)
        {
            System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
            if (propertyInfoName.PropertyType.FullName == "System.Int32")
            {
                propertyInfoName.SetValue(obj, Common.ToInt32(value), null);
            }
            else if (propertyInfoName.PropertyType.FullName == "System.Decimal")
            {
                propertyInfoName.SetValue(obj, Common.ToDecimal(value), null);
            }
            else if (propertyInfoName.PropertyType.FullName == "System.Double")
            {
                propertyInfoName.SetValue(obj, Common.ToDecimal(value), null);
            }
            else if (propertyInfoName.PropertyType.FullName == "System.Boolean")
            {
                propertyInfoName.SetValue(obj, Common.ToBoolean(value), null);
            }
            else
            {
                propertyInfoName.SetValue(obj, Common.ToString(value), null);
            }
        }
        #endregion




        #region 加密解密
        const string KEY_64 = "SCSystem";//注意了，是8个字符，64位
        const string IV_64 = "SCSystem";

        public static string Encode(string data)
        {
            if (string.IsNullOrEmpty(data)) return "";
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }

        public static string Decode(string data)
        {
            if (string.IsNullOrEmpty(data)) return "";
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
        #endregion 加密



        /// <summary>
        /// 格式化SAP的日期时间
        /// </summary>
        /// <param name="dateStr">日期部分yyyyMMdd，日期如果为八个0，则表示空</param>
        /// <param name="timeStr">时间部门HHmmss，为空或者Null表示没有时间部分</param>
        /// <returns></returns>
        public static DateTime ParseSAPDateTime(string dateStr, string timeStr)
        {
            DateTime date = new DateTime();
            if (dateStr.Trim() != "00000000" && !string.IsNullOrEmpty(dateStr))//日期不为空才格式化
            {
                if (string.IsNullOrEmpty(timeStr))
                {
                    date = DateTime.ParseExact(dateStr, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                }
                else
                {
                    date = DateTime.ParseExact(dateStr + timeStr, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                }
            }
            return date;
        }


        /// <summary>
        /// 打包下载 2016-05-31 Paco 增加通用的打包下载功能CommonDownload
        /// </summary>
        /// <param name="urls">文件地址</param>
        /// <returns></returns>
        public static byte[] CommonDownload(IEnumerable<string> urls)
        {
            //根据所选文件打包下载
            MemoryStream ms = new MemoryStream();
            byte[] buffer = null;

            //解决中文文件名乱码的问题
            System.Text.Encoding gbk = System.Text.Encoding.GetEncoding("gbk");
            ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage;

            using (ZipFile file = ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器，可以将里面的文件名进行一些处理。默认情况下，会自动根据文件的路径在zip中创建有关的文件夹。
                foreach (var url in urls)
                {
                    file.Add(url);
                }

                file.CommitUpdate();

                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }

            return buffer;
        }

        public static bool IsIPAddress(string ip)
        {
            if (string.IsNullOrEmpty(ip) || ip.Length < 7 || ip.Length > 15) return false;
            string regformat = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(ip);
        }

        public static bool IsIPPort(string port)
        {
            bool isPort = false;
            int portNum;
            isPort = Int32.TryParse(port, out portNum);
            if (isPort && portNum >= 0 && portNum <= 65535)
            {
                isPort = true;
            }
            else
            {
                isPort = false;
            }
            return isPort;
        }

        public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
        {
            #region INameTransform 成员

            public string TransformDirectory(string name)
            {
                return null;
            }

            public string TransformFile(string name)
            {
                return Path.GetFileName(name);
            }

            #endregion
        }
    }

}
